package com.project.hqshorttaxi.controller;

import com.github.pagehelper.PageHelper;
import com.project.hqshorttaxi.aop.TagLog;
import com.project.hqshorttaxi.dto.LoginParam;
import com.project.hqshorttaxi.entity.Login;
import com.project.hqshorttaxi.service.LoginService;
import com.project.hqshorttaxi.util.NetworkUtil;
import com.project.hqshorttaxi.util.PageInfo;
import com.project.hqshorttaxi.util.RestResult;
import com.project.hqshorttaxi.util.TokenEncrypt;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Calendar;
import java.util.Date;

@RestController
@RequestMapping("/api/console/")
public class LoginController {

    @Resource
    LoginService loginService;
    @Autowired
    HttpServletRequest request;

    /**
     * 登录
     */
    @PostMapping("login")
    @TagLog(operation = 1, content = "用户登录")
    public RestResult login(@RequestBody LoginParam param) {
        try {
            Login entity = loginService.getByUserId(param.getUserId());
            if (entity == null) {
                return RestResult.error("登录用户不存在");
            } else {
                BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
                if (!passwordEncoder.matches(param.getPassword(), entity.getPassword())) {
                    return RestResult.error("密码不正确");
                }
                Calendar calendar = Calendar.getInstance();
                calendar.add(Calendar.DAY_OF_MONTH, 1);
                entity.setToken(TokenEncrypt.sha1(param.getUserId() + DateFormatUtils.format(calendar.getTime(), "yyyyMMddHHmmss")));
                entity.setExpirationDate(calendar.getTime());
                entity.setUpdateTime(new Date());
                entity.setIp(NetworkUtil.getIpAddress(request));
                loginService.update(entity);
                return RestResult.ok("OK", entity.getToken());
            }
        } catch (Exception e) {
            return RestResult.error(e.getMessage());
        }
    }

    /**
     * 新增用户
     */
    @PostMapping("user/add")
    @TagLog(operation = 2, content = "新增用户")
    public RestResult userAdd(@RequestBody Login param) {
        try {
            Login entity = loginService.getByUserId(param.getUserId());
            if (entity != null) {
                return RestResult.error("登录ID已经存在");
            } else {
                BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
                param.setPassword(passwordEncoder.encode("111111"));
                loginService.insert(param);
                return RestResult.ok();
            }
        } catch (Exception e) {
            return RestResult.error(e.getMessage());
        }
    }

    /**
     * 更新用户
     */
    @PostMapping("user/update")
    @TagLog(operation = 3, content = "更新用户")
    public RestResult userUpdate(@RequestBody Login param) {
        try {
            Login entity = loginService.getById(param.getId());
            if (entity == null) {
                return RestResult.error("用户不存在");
            } else {
                loginService.update(param);
                return RestResult.ok();
            }
        } catch (Exception e) {
            return RestResult.error(e.getMessage());
        }
    }

    /**
     * 删除用户
     */
    @PostMapping("user/delete/{id}")
    @TagLog(operation = 4, content = "删除用户")
    public RestResult userDelete(@PathVariable Integer id) {
        try {
            Login entity = loginService.getById(id);
            if (entity == null) {
                return RestResult.error("用户不存在");
            } else {
                if ("admin".equals(entity.getUserId())) {
                    return RestResult.error("此用户无法删除");
                }
                entity.setDeleteFlag(1);
                loginService.update(entity);
                return RestResult.ok();
            }
        } catch (Exception e) {
            return RestResult.error(e.getMessage());
        }
    }

    /**
     * 更新用户密码
     */
    @PostMapping("user/updatePassword")
    @TagLog(operation = 3, content = "更新用户密码")
    public RestResult updatePassword(@RequestHeader(value = "authorization") String token, @RequestBody LoginParam param) {
        try {
            Login entity = loginService.getByToken(token);
            if (entity == null) {
                return RestResult.error("用户不存在");
            }
            BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
            if (!passwordEncoder.matches(param.getPasswordOld(), entity.getPassword())) {
                return RestResult.error("原密码不正确");
            }
            entity.setPassword(passwordEncoder.encode(param.getPassword()));
            loginService.update(entity);
            return RestResult.ok();
        } catch (Exception e) {
            return RestResult.error(e.getMessage());
        }
    }

    /**
     * 用户列表
     */
    @PostMapping("user/page")
    @TagLog(operation = 0, content = "查询用户列表")
    public RestResult page(@RequestBody LoginParam param) {
        PageHelper.startPage(param.getPageNum(), param.getPageSize());
        return RestResult.ok(new PageInfo<>(loginService.list(param)));
    }

    /**
     * 根据ID获取用户
     */
    @GetMapping("user/{id}")
    @TagLog(operation = 0, content = "根据ID获取用户详细信息")
    public RestResult pageById(@PathVariable Integer id) {
        return RestResult.ok(loginService.getById(id));
    }


    /**
     * 重置用户密码
     */
    @PostMapping("user/resetPassword/{id}")
    @TagLog(operation = 3, content = "重置用户密码")
    public RestResult resetPassword(@PathVariable Integer id) {
        try {
            Login entity = loginService.getById(id);
            if (entity == null) {
                return RestResult.error("用户不存在");
            }
            BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
            entity.setPassword(passwordEncoder.encode("111111"));
            loginService.update(entity);
            return RestResult.ok();
        } catch (Exception e) {
            return RestResult.error(e.getMessage());
        }
    }
}
